package com.joysuch.wwyt.bp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joysuch.wwyt.bp.entity.BpInspectionNotifyConfig;
import com.joysuch.wwyt.bp.job.BpInspectionNotifyJob;
import com.joysuch.wwyt.bp.service.BpInspectionNotifyConfigService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.enums.UserRoleTypes;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author A
 * 2022-07-06
 */
@RestController
@RequestMapping("bp/bpinspection/notify-config")
public class BpInspectionNotifyConfigController {

    @Resource
    private BpInspectionNotifyConfigService service;
    @Resource
    private BpInspectionNotifyJob job;

    @GetMapping("/all")
    public ResultBean all() {
        LambdaQueryWrapper<BpInspectionNotifyConfig> query = new LambdaQueryWrapper<>();
        query.eq(BpInspectionNotifyConfig::getDeleteFlag, "0");
        return ResultBean.success(service.list(query));
    }

    @PostMapping("/add")
    public synchronized ResultBean add(@RequestBody BpInspectionNotifyConfig config) {
        LambdaQueryWrapper<BpInspectionNotifyConfig> query = new LambdaQueryWrapper<>();
        query.eq(BpInspectionNotifyConfig::getDeleteFlag, "0");
        query.eq(BpInspectionNotifyConfig::getRole, config.getRole());
        BpInspectionNotifyConfig cfg = service.getOne(query);
        if (cfg != null) {
            return ResultBean.fail(-1, UserRoleTypes.getRoleNameByIndex(config.getRole()) + "已被配置过，不可重复添加");
        }

        service.save(config);
        return ResultBean.defaultSuccessResult();
    }

    @PostMapping("/edit")
    public synchronized ResultBean edit(@RequestBody BpInspectionNotifyConfig config) {
        LambdaQueryWrapper<BpInspectionNotifyConfig> query = new LambdaQueryWrapper<>();
        query.eq(BpInspectionNotifyConfig::getDeleteFlag, "0");
        query.eq(BpInspectionNotifyConfig::getId, config.getId());
        BpInspectionNotifyConfig cfg = service.getOne(query);
        if (cfg != null) {
            cfg.setNotifyDate(config.getNotifyDate());
            cfg.setPeriod(config.getPeriod());
            cfg.setTimes(config.getTimes());
            service.saveOrUpdate(cfg);
        }
        return ResultBean.defaultSuccessResult();
    }

    @PostMapping("/delete")
    public synchronized ResultBean delete(@RequestBody BpInspectionNotifyConfig config) {
        service.removeById(config.getId());
        return ResultBean.defaultSuccessResult();
    }

    @GetMapping("/test-job")
    public ResultBean testJob() {
        job.runTask();
        return ResultBean.defaultSuccessResult();
    }

}
